using DesktopWidgetApp.Shared;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DesktopWidgetApp.Core.Data
{
    /// <summary>
    /// SQLite状态仓储实现
    /// </summary>
    public class SqliteStatusRepository : SqliteRepositoryBase<Status>, IStatusRepository
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="databasePath">数据库路径</param>
        public SqliteStatusRepository(string databasePath) : base(databasePath)
        {
        }

        /// <summary>
        /// 获取指定用户的所有状态记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>状态记录列表</returns>
        public async Task<IEnumerable<Status>> GetByUserIdAsync(Guid userId)
        {
            return await _database.Table<Status>().Where(s => s.UserId == userId).OrderByDescending(s => s.StartTime).ToListAsync();
        }

        /// <summary>
        /// 获取指定用户的当前状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>当前状态</returns>
        public async Task<Status> GetCurrentStatusByUserIdAsync(Guid userId)
        {
            return await _database.Table<Status>().Where(s => s.UserId == userId && s.EndTime == null).OrderByDescending(s => s.StartTime).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 获取指定类型的所有状态
        /// </summary>
        /// <param name="statusType">状态类型</param>
        /// <returns>指定类型的状态列表</returns>
        public async Task<IEnumerable<Status>> GetByStatusTypeAsync(StatusType statusType)
        {
            return await _database.Table<Status>().Where(s => s.Type == statusType).OrderByDescending(s => s.StartTime).ToListAsync();
        }

        /// <summary>
        /// 获取免打扰状态的所有用户
        /// </summary>
        /// <returns>免打扰状态的用户ID列表</returns>
        public async Task<IEnumerable<Guid>> GetDoNotDisturbUserIdsAsync()
        {
            var statuses = await _database.Table<Status>().Where(s => s.IsDoNotDisturb && s.EndTime == null).ToListAsync();
            return statuses.Select(s => s.UserId).Distinct();
        }

        /// <summary>
        /// 结束用户的当前状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="endTime">结束时间</param>
        public async Task EndCurrentStatusAsync(Guid userId, DateTime endTime)
        {
            var currentStatus = await GetCurrentStatusByUserIdAsync(userId);
            if (currentStatus != null)
            {
                currentStatus.EndTime = endTime;
                await _database.UpdateAsync(currentStatus);
            }
        }
    }
}